<?php

class BlogPost{
    public function getPosts(){
        $result = Sql::init("posts")->query();
        
        return  HttpData::result('json', 200, "success", $result, 30);
    }
    public function getPost(){
        //get post by id
        $id = Request::get("id");
        $result = Sql::init("posts")->where(array("id"=>$id))->query();
        
        return  HttpData::result('json', 200, "success", $result, 10);
    }
    public function createPost(){
        global $auth;
        //create post
        // CREATE TABLE posts (
        //     id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        //     title VARCHAR(255) NOT NULL,
        //     content TEXT,
        //     created_at INT NOT NULL,
        //     updated_at INT NOT NULL,
        //     ip VARCHAR(255) NOT NULL,
        //     userID INT NOT NULL
        // );
        //鉴权
        if (!$auth){
            return  HttpData::result('json', 401, "error", null);
        }
        $title = Request::post("title");
        $content = Request::post("content");
        $ip = $_SERVER['REMOTE_ADDR'];
        $userID = Request::post("userID");
        $created_at = time();
        $updated_at = time();
        $result = Sql::init("posts")->setData(array("title"=>$title, "content"=>$content, "created_at"=>$created_at, "updated_at"=>$updated_at, "ip"=>$ip, "userID"=>$userID))->insert();
        if ($result){
            return  HttpData::result('json', 200, "success", null);
        }else{
            return  HttpData::result('json', 500, "error", null);
        }


    }
}